import 'dart:typed_data';
import 'package:animations/animations.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:ui' as ui;

import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/entity/product_entity.dart';
import 'package:yp/helper.dart';
import 'package:yp/router.dart';

import 'share_logic.dart';
import 'share_state.dart';

class ShareDialogSheet {
  static ShareLogic logic;
  // static final ShareLogic logic = Get.find<ShareLogic>();
  static final ShareState state = Get.find<ShareLogic>().state;

  static GlobalKey repaintWidgetKey = GlobalKey();
  static String name = SpUtil.getString('empeName') ?? '';
  static int tabIndex;

  // static TabController mTabController;

  static void showShareDialog(BuildContext context, item) {
    // mTabController = tabController;
    logic = Get.put(ShareLogic());
    state.tabController.index = 0;
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.0),
      ),
      isScrollControlled: true,
      builder: (BuildContext context) {
        return buildModal(context, item);
      },
    );
  }

  static Widget buildModal(BuildContext context, ProductEntity item) {
    return Stack(
      children: [
        Container(
          height: 1100.w,
          width: 750.w,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(height: 50.w),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // Text(
                  //   "分享后可赚",
                  //   style: TextStyle(
                  //     fontSize: 32.sp,
                  //     color: Color(0xff222222),
                  //   ),
                  // ),
                  // Text(
                  //   "¥${item.commissionAmount}",
                  //   style: TextStyle(
                  //     fontSize: 32.sp,
                  //     color: Config.mainColor,
                  //   ),
                  // )
                ],
              ),
              Container(
                height: 90.w,
                margin: EdgeInsets.only(top: 20.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(
                    bottom: BorderSide(
                      color: Color(0xffeeeeee),
                      width: 1.w,
                    ),
                  ),
                ),
                child: TabBar(
                  onTap: (index) {
                    // tabIndex = index;
                    if (index == 1) {
                      tabIndex = 0;
                      logic.showQrcode(item);
                      Navigator.pop(context);
                      showModal(
                        context: context,
                        //动画过渡配置
                        configuration: FadeScaleTransitionConfiguration(
                          //阴影背景颜色
                          barrierColor: Colors.black54,
                          //打开新的Widget 的时间
                          transitionDuration: Duration(milliseconds: 1000),
                          //关闭新的Widget 的时间
                          reverseTransitionDuration:
                              Duration(milliseconds: 1000),
                        ),
                        builder: (BuildContext context) {
                          //显示的Widget
                          return buildQrcodeModal(context, item);
                        },
                      );
                    }
                  },
                  controller: state.tabController,
                  isScrollable: false,
                  indicatorColor: Config.mainColor,
                  indicatorWeight: 3.0,
                  indicator: UnderlineTabIndicator(
                    insets: EdgeInsets.only(left: 180.w, right: 180.w),
                    borderSide: BorderSide(width: 6.w, color: Config.mainColor),
                  ),
                  unselectedLabelColor: Color(0xff999999),
                  indicatorPadding: EdgeInsets.symmetric(horizontal: 30.w),
                  labelStyle: TextStyle(
                    fontSize: 28.sp,
                    color: Color(0xff666666),
                  ),
                  labelColor: Colors.black,
                  tabs: <Widget>[
                    Tab(text: "推广图文"),
                    Tab(text: "商品海报"),
                  ],
                ),
              ),
              Container(
                width: 690.w,
                margin: EdgeInsets.symmetric(vertical: 30.w),
                padding: EdgeInsets.all(15.w),
                decoration: BoxDecoration(
                  color: Color(0xfff6f6f6),
                  borderRadius: BorderRadius.all(
                    Radius.circular(10.w),
                  ),
                ),
                child: Text(
                  "${item.itemName}",
                  style: TextStyle(
                    fontSize: 26.sp,
                    color: Color(0xff222222),
                  ),
                ),
              ),

              /// image
              Container(
                height: 180.w,
                width: 750.w,
                child: ListView.builder(
                  shrinkWrap: true,
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (ctx, i) {
                    return Container(
                      width: 180.w,
                      height: 180.w,
                      margin: EdgeInsets.only(left: 30.w),
                      child: item.imageSrc != null
                          ? Image.network(
                              "${item.imageSrc}",
                              width: 180.w,
                              height: 180.w,
                            )
                          : Container(
                              width: 180.w,
                              height: 180.w,
                            ),
                    );
                  },
                  itemCount: 1,
                ),
              ),

              Container(
                height: 56.w,
                width: 172.w,
                margin: EdgeInsets.only(top: 30.w, bottom: 80.w),
                decoration: BoxDecoration(
                  color: Config.mainColor,
                  borderRadius: BorderRadius.all(
                    Radius.circular(100),
                  ),
                ),
                child: GestureDetector(
                  onTap: () async {
                    bool hasLocationPermission =
                        await requestLocationPermission();
                    if (hasLocationPermission) {
                      Navigator.pop(context);
                      var resp = await Dio().get(item.imageSrc,
                          options: Options(responseType: ResponseType.bytes));
                      var success = await ImageGallerySaver.saveImage(
                          Uint8List.fromList(resp.data));
                      ClipboardData data =
                          new ClipboardData(text: item.itemName);
                      Clipboard.setData(data);
                      toast('保存成功');
                      print("定位权限申请通过");
                    } else {
                      print("定位权限申请不通过");
                    }
                  },
                  child: Center(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          "assets/images/download.png",
                          width: 24.w,
                        ),
                        SizedBox(width: 10.w),
                        Text(
                          "保存图文",
                          style: TextStyle(
                            fontSize: 24.sp,
                            color: Colors.white,
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 60.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      children: [
                        GestureDetector(
                          onTap: () {
                            if (item.imageSrc == null || item.imageSrc == "") {
                              toast("分享失败，未获取到图片地址");
                              return;
                            }
                            var data;
                            if (item.isPreSale == 1) {
                              data =
                                  '/pages/index?currentShopId=${item.ecShopNumId}&mberType=2&applyerId=${state.userId}&otherguide=false&isGopreSale=1&style_num_id=${item.styleNumId}&itemid=${item.itemNumId}';
                            } else {
                              data =
                                  '/pages/index?currentShopId=${item.ecShopNumId}&mberType=2&applyerId=${state.userId}&otherguide=false&isGoGoodDetail=true&style_num_id=${item.styleNumId}&itemid=${item.itemNumId}';
                            }
                            var model = new WeChatShareMiniProgramModel(
                              path: data,
                              webPageUrl: 'www.baidu.com',
                              userName: Config.MINI_ACCOUNT,
                              // miniProgramType: WXMiniProgramType.RELEASE,
                              miniProgramType: WXMiniProgramType.RELEASE,
                              title: item.itemName,
                              description: item.itemName,
                              thumbnail: WeChatImage.network(
                                "${item.imageSrc}",
                              ),
                            );
                            fluwx.shareToWeChat(model);
                          },
                          child: Image.asset(
                            "assets/images/share1.png",
                            width: 88.w,
                          ),
                        ),
                        Text(
                          "微信好友",
                          style: TextStyle(
                            fontSize: 22.sp,
                            color: Color(0xff666666),
                            height: 2.5,
                          ),
                        )
                      ],
                    ),
                    GestureDetector(
                      onTap: () {
                        // Navigator.pop(context);
                        // Get.toNamed(RouteConfig.materialCreate,
                        //     arguments: {'item': item});
                        // 处理发布到朋友圈
                        if (item.imageSrc == null || item.imageSrc == "") {
                          toast("分享失败，未获取到图片地址");
                          return;
                        }
                        print('---------------分享朋友圈--------------------');
                        print(item);
                        var data;
                        if (item.isPreSale == 1) {
                          data = Config.WEB_URL +
                              '/goods_detail?item_num_id=${item.itemNumId}&style_num_id=${item.styleNumId}&shop_id=${item.ecShopNumId}';
                          // '/pages/index?currentShopId=${item.ecShopNumId}&mberType=2&applyerId=${state.userId}&otherguide=false&isGopreSale=1&style_num_id=${item.styleNumId}&itemid=${item.itemNumId}';
                        } else {
                          data = Config.WEB_URL +
                              '/goods_detail?item_num_id=${item.itemNumId}&style_num_id=${item.styleNumId}&shop_id=${item.ecShopNumId}';
                          // '/pages/index?currentShopId=${item.ecShopNumId}&mberType=2&applyerId=${state.userId}&otherguide=false&isGoGoodDetail=true&style_num_id=${item.styleNumId}&itemid=${item.itemNumId}';
                        }
                        var model = fluwx.WeChatShareWebPageModel(
                          data,
                          description: item.itemName,
                          title: item.itemName,
                          thumbnail: fluwx.WeChatImage.network(item.imageSrc),
                          scene: fluwx.WeChatScene.TIMELINE,
                        );
                        fluwx.shareToWeChat(model);
                      },
                      child: Column(
                        children: [
                          Image.asset(
                            "assets/images/share4.png",
                            width: 88.w,
                          ),
                          Text(
                            "朋友圈",
                            style: TextStyle(
                              fontSize: 22.sp,
                              color: Color(0xff666666),
                              height: 2.5,
                            ),
                          )
                        ],
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                        Get.toNamed(RouteConfig.materialCreate,
                            arguments: {'item': item});
                      },
                      child: Column(
                        children: [
                          Image.asset(
                            "assets/images/share2.png",
                            width: 88.w,
                          ),
                          Text(
                            "发布自定义素材",
                            style: TextStyle(
                              fontSize: 22.sp,
                              color: Color(0xff666666),
                              height: 2.5,
                            ),
                          )
                        ],
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                        logic.showQrcode(item);
                        showModal(
                          context: context,
                          //动画过渡配置
                          configuration: FadeScaleTransitionConfiguration(
                            //阴影背景颜色
                            barrierColor: Colors.black54,
                            //打开新的Widget 的时间
                            transitionDuration: Duration(milliseconds: 1000),
                            //关闭新的Widget 的时间
                            reverseTransitionDuration:
                                Duration(milliseconds: 1000),
                          ),
                          builder: (BuildContext context) {
                            //显示的Widget
                            return buildQrcodeModal(context, item);
                          },
                        );
                      },
                      child: Column(
                        children: [
                          Image.asset(
                            "assets/images/share3.png",
                            width: 88.w,
                          ),
                          Text(
                            "生成商品海报",
                            style: TextStyle(
                              fontSize: 22.sp,
                              color: Color(0xff666666),
                              height: 2.5,
                            ),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
              // GestureDetector(
              //   onTap: () {
              //     Get.toNamed(RouteConfig.home);
              //   },
              //   child: Container(
              //     height: 60.w,
              //     width: 200.w,
              //     margin: EdgeInsets.only(top: 80.w, bottom: 50.w),
              //     decoration: BoxDecoration(
              //       border: Border.all(
              //         color: Color(0xffd8d8d8),
              //       ),
              //       borderRadius: BorderRadius.all(
              //         Radius.circular(100),
              //       ),
              //     ),
              //     child: Center(
              //       child: Text(
              //         "网格员中心",
              //         style: TextStyle(
              //           fontSize: 28.sp,
              //           color: Color(0xff222222),
              //         ),
              //       ),
              //     ),
              //   ),
              // ),
            ],
          ),
        ),
        Positioned(
          right: 30.w,
          top: 30.w,
          child: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Image.asset(
              "assets/images/closemodal.png",
              width: 32.w,
            ),
          ),
        ),
      ],
    );
  }

  static Widget buildQrcodeModal(BuildContext context, ProductEntity item) {
    return GetBuilder<ShareLogic>(
      builder: (logic) {
        return Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Align(
                child: GestureDetector(
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Padding(
                    padding: EdgeInsets.only(right: 30.w),
                    child: Image.asset(
                      "assets/images/closeqrcode.png",
                      width: 60.w,
                    ),
                  ),
                ),
                alignment: Alignment.centerRight,
              ),
              SizedBox(height: 20.w),
              RepaintBoundary(
                key: repaintWidgetKey,
                child: Container(
                  width: 654.w,
                  height: 1000.w,
                  padding: EdgeInsets.symmetric(
                    vertical: 25.w,
                    horizontal: 25.w,
                  ),
                  decoration: BoxDecoration(
                      image: DecorationImage(
                    image: AssetImage("assets/images/qrcode.png"),
                    fit: BoxFit.fitWidth,
                  )),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.all(
                              Radius.circular(100.w),
                            ),
                            child: Image.asset(
                              "assets/images/avatar.png",
                              width: 64.w,
                            ),
                          ),
                          SizedBox(
                            width: 20.w,
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                name,
                                style: TextStyle(
                                  fontSize: 30.sp,
                                  color: Colors.white,
                                ),
                              ),
                              Text(
                                "为您挑选了一个好物～",
                                style: TextStyle(
                                  fontSize: 22.sp,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          )
                        ],
                      ),
                      Container(
                        margin: EdgeInsets.only(
                          top: 60.w,
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: 35.w,
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            item.imageSrc != null && item.imageSrc != ""
                                ? Image.network(
                                    item.imageSrc,
                                    width: 530.w,
                                    height: 520.w,
                                  )
                                : Container(
                                    width: 530.w,
                                    height: 520.w,
                                  ),
                            SizedBox(
                              height: 20.w,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                RichText(
                                  text: TextSpan(
                                    children: [
                                      TextSpan(
                                        text: '折后价 ¥',
                                        style: TextStyle(
                                          color: Color(0xffD0021B),
                                          fontSize: 24.w,
                                        ),
                                      ),
                                      TextSpan(
                                        text: item.expectPrice != null &&
                                                item.expectPrice > 0
                                            ? item.expectPrice.toString()
                                            : item.price.toString(),
                                        style: TextStyle(
                                          color: Color(0xffD0021B),
                                          fontSize: 38.w,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Text(
                                  "已售${item.soldQuantity.toString().replaceAll(".0", "")}件",
                                  style: TextStyle(
                                    fontSize: 24.sp,
                                    color: Color(0xffA3A3A3),
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(
                              height: 20.w,
                            ),
                            item.marketPrice > 0
                                ? Text(
                                    '¥${item.marketPrice.toString()}',
                                    style: TextStyle(
                                      fontSize: 28.sp,
                                      color: Color(0xffA3A3A3),
                                      decoration: TextDecoration.lineThrough,
                                    ),
                                  )
                                : SizedBox(),
                            SizedBox(
                              height: 10.w,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Container(
                                  width: 300.w,
                                  child: Text(
                                    '${item.itemName}',
                                    style: TextStyle(
                                      fontSize: 28.sp,
                                      color: Color(0xff262626),
                                    ),
                                    maxLines: 3,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                if (state.qrCode != null && state.qrCode != "")
                                  ClipRRect(
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(100.w),
                                    ),
                                    child: Image.network(
                                      state.qrCode,
                                      width: 140.w,
                                    ),
                                  ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              GestureDetector(
                onTap: () async {
                  bool hasLocationPermission =
                      await requestLocationPermission();
                  if (hasLocationPermission) {
                    BuildContext buildContext = repaintWidgetKey.currentContext;
                    RenderRepaintBoundary boundary =
                        buildContext.findRenderObject();
                    ui.Image image = await boundary.toImage(pixelRatio: 3.0);
                    ByteData byteData =
                        await image.toByteData(format: ui.ImageByteFormat.png);
                    final result = await ImageGallerySaver.saveImage(
                        byteData.buffer.asUint8List());
                    print(result);
                    // toast('保存成功');
                    Navigator.pop(context);
                    print("定位权限申请通过");
                  } else {
                    print("定位权限申请不通过");
                  }
                  showModal(
                    context: context,
                    //动画过渡配置
                    configuration: FadeScaleTransitionConfiguration(
                      //阴影背景颜色
                      barrierColor: Colors.black54,
                      //打开新的Widget 的时间
                      transitionDuration: Duration(milliseconds: 1000),
                      //关闭新的Widget 的时间
                      reverseTransitionDuration: Duration(milliseconds: 1000),
                    ),
                    builder: (BuildContext context) {
                      //显示的Widget
                      return buildSuccessModal(context);
                    },
                  );
                },
                child: Container(
                  width: 400.w,
                  height: 88.w,
                  margin: EdgeInsets.only(top: 30.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(100),
                    ),
                    border: Border.all(color: Colors.white),
                  ),
                  child: Center(
                    child: Text(
                      "保存图片",
                      style: TextStyle(
                        fontSize: 34.sp,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }

  static Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.storage.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //如果客户拒绝过一次，则不再申请权限
      if (SpUtil.getBool('Permissionstoragestatus')==true )
      {
        toast('请在手机设置中授予存储访问权限');
        return false;
      }
      //未授权则发起一次申请
      status = await Permission.storage.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        SpUtil.putBool('Permissionstoragestatus',true);
        return false;
      }
    }
  }

  static Center buildSuccessModal(BuildContext context) {
    return Center(
      child: Container(
        width: 490.w,
        height: 400.w,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(
            Radius.circular(30.w),
          ),
        ),
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.only(left: 50.w),
              child: Column(
                children: [
                  SizedBox(height: 70.w),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Image.asset(
                        "assets/images/save.png",
                        width: 30.w,
                      ),
                      SizedBox(width: 20.w),
                      Text(
                        "文案已复制",
                        style: TextStyle(
                          fontSize: 28.sp,
                          color: Color(0xff222222),
                        ),
                      )
                    ],
                  ),
                  SizedBox(height: 40.w),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Image.asset(
                        "assets/images/save.png",
                        width: 30.w,
                      ),
                      SizedBox(width: 20.w),
                      Text(
                        "图片已保存到相册",
                        style: TextStyle(
                          fontSize: 28.sp,
                          color: Color(0xff222222),
                        ),
                      )
                    ],
                  ),
                  SizedBox(height: 40.w),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Image.asset(
                        "assets/images/save.png",
                        width: 30.w,
                      ),
                      SizedBox(width: 20.w),
                      Text(
                        "素材已分享到动态",
                        style: TextStyle(
                          fontSize: 28.sp,
                          color: Color(0xff222222),
                        ),
                      )
                    ],
                  ),
                  SizedBox(height: 50.w),
                ],
              ),
            ),
            Divider(
              color: Color(0xffeeeeee),
              height: .2,
            ),
            SizedBox(height: 10.w),
            InkWell(
              onTap: () {
                Navigator.pop(context);
              },
              child: Container(
                width: 750.w,
                child: Center(
                  child: Text(
                    "我知道了",
                    style: TextStyle(
                      fontSize: 32.sp,
                      color: Config.mainColor,
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
